<template>
  <div>
    <el-dialog title="详情" append-to-body :visible.sync="visible" @close="closeDialog" :fullscreen="true" :close-on-press-escape="false">
      <div v-loading="loading">
        <div class="groups">
          <div class="titleIcon">
            <i class="el-icon-vertical-bar avue-group__icon"></i>
            <h4>基本信息</h4>
          </div>
        </div>
        <avue-form ref="basicInfoForm" v-model="basicInfoForm" :option="basicInfoOption"></avue-form>
        <div v-if="basicInfoForm.examineMode === 'SAMPLING'" class="groups">
          <div class="titleIcon">
            <i class="el-icon-vertical-bar avue-group__icon"></i>
            <h4>抽样信息</h4>
          </div>
        </div>
        <avue-form ref="sampleInfoForm" v-show="basicInfoForm.examineMode === 'SAMPLING'" v-model="sampleInfoForm" :option="sampleInfoOption"></avue-form>

        <div class="title-result">
          <div class="title">
            <i class="el-icon-vertical-bar avue-group__icon"></i>
            <h4>检验结果</h4>
          </div>
        </div>
        <avue-form ref="inspectionResultsRecordForm" v-model="inspectionResultsRecordForm" :option="inspectionResultsRecordOption" :upload-preview="uploadPreview"> </avue-form>
        <div v-if="inspectionResultsRecordForm.examineResult === 'NG'" class="groups">
          <div class="titleIcon">
            <i class="el-icon-vertical-bar avue-group__icon"></i>
            <h4>不良记录</h4>
          </div>
        </div>
        <avue-crud v-if="inspectionResultsRecordForm.examineResult === 'NG'" ref="bnormalRecordCrud" :option="failureRecordOption" :data="failureRecordData"> </avue-crud>
      </div>
      <div slot="footer">
        <el-button size="small" @click="closeDialog"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </div>
    </el-dialog>
    <el-dialog
      ref="dialog"
      title="查看PDF"
      append-to-body
      :visible.sync="showEsopDialog"
      :full-screen="fullScreen"
      :class="[fullScreen ? 'fullscreen' : 'no_fullScreen']"
      :close-on-click-modal="false"
      @close="fullScreen = false"
    >
      <iframe ref="pdf" :src="pdfUrl" width="100%" :height="iframeHeight"></iframe>
      <div slot="title" class="dialog-title">
        <span class="title">查看PDF</span>
        <span class="el-dialog__close fullscreen-icon" @click="fullScreen = !fullScreen">
          <i class="el-icon-full-screen"></i>
        </span>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="showEsopDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <doc-preview :url="fileUrl" :visiable.sync="previewVisible" :file-type="fileType"></doc-preview>
  </div>
</template>

<script>
import { getDetail } from '@/api/quality/incomingMaterialsToBeInspected';
import DocPreview from '@/components/filePreview/docPreview';
import { downLoad } from '@/api/resource/attach';
export default {
  name: 'iqc-inspection-records-detail',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  components: {
    DocPreview
  },
  data() {
    return {
      loading: false,
      failureRecordData: [],
      fileType: '',
      fileUrl: '',
      pdfUrl: '',
      previewVisible: false,
      showEsopDialog: false,
      fullScreen: '',
      basicInfoForm: {},
      basicInfoOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 160,
        column: [
          {
            label: '检验单号',
            prop: 'documentNo',
            disabled: true,
            span: 8
          },
          {
            label: '单据号',
            prop: 'sourceNo',
            disabled: true,
            span: 8
          },
          {
            label: '供应商名称',
            prop: 'partnerName',
            disabled: true,
            span: 8
          },
          {
            label: '物料编码',
            prop: 'partNo',
            disabled: true,
            span: 8
          },
          {
            label: '物料名称',
            prop: 'partName',
            disabled: true,
            span: 8
          },
          {
            label: '检验方式',
            prop: 'examineMode',
            disabled: true,
            span: 8,
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=inspection_mode',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            clearable: false,
            change: (val) => {
              this.changeNgQuantity(val.value, this.inspectionResultsRecordForm.ngQuantity);
            }
          },
          {
            label: '送检日期',
            prop: 'sendExamineDate',
            disabled: true,
            span: 8
          },
          {
            label: '收料数量',
            prop: 'sendExamineQuantity',
            disabled: true,
            span: 8
          },
          {
            label: '检验人员',
            prop: 'examineByName',
            type: 'search',
            disabled: true,
            span: 8,
            appendClick: () => {
              if (this.openHandleDialogType === 'edit') {
                this.openUserCommonModal();
              }
            }
          }
        ]
      },
      sampleInfoForm: {},
      sampleInfoOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 160,
        column: [
          {
            label: 'AQL配置方案编码',
            prop: 'code',
            disabled: true,
            span: 8,
            type: 'select',
            dicData: [],
            clearable: false,
            change: (val) => {
              this.changeAqlCode(val.value);
            }
          },
          {
            label: 'AQL配置方案名称',
            prop: 'name',
            disabled: true,
            span: 8
          },
          {
            label: '抽样标准',
            prop: 'samplingStandard',
            disabled: true,
            span: 8
          },
          {
            label: '严格程度',
            prop: 'severityCode',
            disabled: true,
            span: 8,
            type: 'select',
            dicData: [
              { label: '正常', value: 'NORMAL' },
              { label: '放宽', value: 'REDUCE' },
              { label: '加严', value: 'TIGHTEN' }
            ]
          },
          {
            label: '检验水平',
            prop: 'levelType',
            disabled: true,
            span: 8,
            type: 'select',
            dicData: [
              { label: '特殊检验水平', value: 'SPECIAL' },
              { label: '一般检验水平', value: 'GENERAL' }
            ],
            change: (val) => {
              const levelCode = this.findObject(this.sampleInfoOption.column, 'levelCode');
              if (val.value === 'SPECIAL') {
                levelCode.dicData = [
                  { label: 'S-1', value: 'S-1' },
                  { label: 'S-2', value: 'S-3' },
                  { label: 'S-3', value: 'S-3' },
                  { label: 'S-4', value: 'S-4' }
                ];
              } else {
                levelCode.dicData = [
                  { label: 'I', value: 'I' },
                  { label: 'II', value: 'II' },
                  { label: 'III', value: 'III' }
                ];
              }
            }
          },
          {
            label: '检验水平代码',
            prop: 'levelCode',
            dicData: [],
            disabled: true,
            span: 8
          },
          {
            label: '质量水平代码',
            prop: 'limitCode',
            disabled: true,
            span: 8
          },
          {
            label: '严重缺陷抽样数量字码',
            prop: 'severityLimitCode',
            disabled: true,
            span: 8
          },
          {
            label: '主要缺陷抽样数量字码',
            prop: 'majorLimitCode',
            disabled: true,
            span: 8
          },
          {
            label: '次要缺陷抽样数量字码',
            prop: 'minorLimitCode',
            disabled: true,
            span: 8
          },
          {
            label: '检验数量',
            prop: 'sampleQuantity',
            disabled: true,
            span: 8
          },
          {
            label: '接收数量（Ac）',
            prop: 'acQuantity',
            disabled: true,
            span: 8
          },
          {
            label: '拒绝数量（Re）',
            prop: 'reQuantity',
            disabled: true,
            span: 8
          }
        ]
      },
      inspectionResultsRecordForm: {},
      inspectionResultsRecordOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 150,
        column: [
          {
            label: '综合判断',
            prop: 'examineResult',
            span: 8,
            type: 'select',
            disabled: true,
            dicData: [
              { label: 'OK', value: 'OK' },
              { label: 'NG', value: 'NG' }
            ],
            clearable: false,
            rules: [
              {
                required: true,
                message: '请选择 综合判断',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '不合格数量',
            prop: 'ngQuantity',
            type: 'number',
            disabled: true,
            min: 0,
            span: 8,
            change: (val) => {
              this.changeNgQuantity(this.basicInfoForm.examineMode, val.value);
            },
            rules: [
              {
                validator: this.validateNgQuantity,
                trigger: 'blur'
              }
            ]
          },
          {
            label: '合格数量',
            prop: 'okQuantity',
            span: 8,
            disabled: true
          },
          {
            label: '查看检验报告',
            prop: 'attachments',
            dataType: 'object',
            disabled: true,
            type: 'upload',
            span: 16,
            // loadText: '图片上传中，请稍等',
            propsHttp: {
              url: 'link',
              name: 'originalName',
              res: 'data'
            },
            // listType: 'picture-card',
            // accept: 'image/png, image/jpeg, image/jpg',
            // tip: '只能上传png/jpeg/jpg文件',
            action: '/api/blade-resource/oss/endpoint/put-file-attach',
            rules: [
              {
                required: true,
                message: '请上传检验报告',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            span: 24,
            maxRows: 3,
            minRows: 3
          }
        ]
      },
      failureRecordOption: {
        height: '300',
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        indexLabel: '序号',
        selection: true,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        viewBtn: false,
        menu: false,
        refreshBtn: false,
        columnBtn: false,
        column: [
          //   {
          //     label: '包装条码/SN',
          //     prop: 'objectSn'
          //   },
          {
            label: '不良现象',
            prop: 'ngFailureName'
          },
          {
            label: '不良原因（大类）',
            prop: 'ngMainCauseName'
          },
          {
            label: '不良原因（小类）',
            prop: 'ngSubCauseName'
          },
          {
            label: '检验数量',
            prop: 'objectQuantity'
          },
          {
            label: '不良数量',
            prop: 'ngQuantity',
            row: true
          },
          {
            label: '不良说明',
            prop: 'faultDescription'
          },
          {
            label: '改善措施',
            prop: 'improvementMeasure'
          }
        ]
      }
    };
  },
  computed: {
    iframeHeight() {
      const docHeight = document.documentElement.clientHeight;
      const iframeHeight = docHeight - 188 + 'px';
      return this.fullScreen ? iframeHeight : '600px';
    }
  },
  methods: {
    closeDialog() {
      // this.$refs.basicInfoForm.resetFields();
      // this.basicInfoForm = {};
      // if (this.basicInfoForm.examineMode === 'SAMPLING') {
      //   this.$refs.sampleInfoForm.resetFields();
      //   this.sampleInfoForm = {};
      // }
      this.$refs.inspectionResultsRecordForm.resetFields();
      // this.inspectionResultsRecordForm = {};
      this.failureRecordData = [];
      this.$emit('update:visible', false);
    },
    handleDownload(link) {
      window.open(`${link}`);
    },
    openPreview(index = 0, link) {
      this.$ImagePreview([{ url: link }], index, {
        closeOnClickModal: false
      });
    },
    handleFullScreen() {
      this.fullScreen = !this.fullScreen;
    },

    getFileType(url) {
      // 从URL中提取文件名
      const filename = url.split('/').pop();
      // 提取文件名的扩展名
      const fileExtension = filename.split('.').pop();
      return fileExtension;
    },
    uploadPreview(file, column, done) {
      let url = this._get(file, 'response.data.link', '');
      if (url) {
        file.url = url;
      }
      const fileType = this.getFileType(file.url);
      if (['doc', 'docx', 'xlsx', 'xls'].includes(fileType)) {
        this.previewVisible = true;
        this.fileUrl = file.url;
        this.fileType = fileType;
        return;
      }
      if (file.url.indexOf('pdf') != -1) {
        downLoad({ link: file.url }).then(
          (res) => {
            let fileURL = null;
            var blob = new Blob([res.data], { type: 'application/pdf' });
            if (window.createObjectURL != undefined) {
              // basic
              fileURL = window.createObjectURL(blob);
            } else if (window.webkitURL != undefined) {
              // webkit or chrome
              try {
                fileURL = window.webkitURL.createObjectURL(blob);
              } catch (error) {
                console.log(error);
              }
            } else if (window.URL != undefined) {
              // mozilla(firefox)
              try {
                fileURL = window.URL.createObjectURL(blob);
              } catch (error) {
                console.log(error);
              }
            }
            this.pdfUrl = '/pdf/web/viewer.html?file=' + encodeURIComponent(fileURL);
            this.showEsopDialog = true;
          },
          (error) => {}
        );
      } else {
        if (this.isImageFile(url || file.url)) {
          this.$ImagePreview([{ url: url ? url : file.url }], 0, {
            closeOnClickModal: false
          });
        } else {
          window.open(url || file.url);
        }
      }
    },
    isImageFile(filename) {
      let ext = filename.split('.').pop().toLowerCase();
      return ['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(ext);
    },
    changeNgQuantity(examineMode, val) {
      if (examineMode === 'SAMPLING' && this.sampleInfoForm.sampleQuantity && val != undefined && Number(this.sampleInfoForm.sampleQuantity) >= Number(val)) {
        console.log(this.sampleInfoForm.sampleQuantity, val);
        this.inspectionResultsRecordForm.okQuantity = this.quantityCount(this.sampleInfoForm.sampleQuantity, val, '-');
      } else if (examineMode === 'SAMPLING' && this.sampleInfoForm.sampleQuantity && !val) {
        this.inspectionResultsRecordForm.okQuantity = this.quantityCount(this.sampleInfoForm.sampleQuantity, 0, '-');
      } else if (
        examineMode === 'FULLINSPECTION' &&
        this.basicInfoForm.sendExamineQuantity &&
        val != undefined &&
        Number(this.basicInfoForm.sendExamineQuantity) >= Number(val)
      ) {
        this.inspectionResultsRecordForm.okQuantity = this.quantityCount(this.basicInfoForm.sendExamineQuantity, val, '-');
      } else if (examineMode === 'FULLINSPECTION' && this.basicInfoForm.sendExamineQuantity && !val) {
        this.inspectionResultsRecordForm.okQuantity = this.quantityCount(this.basicInfoForm.sendExamineQuantity, 0, '-');
      }
    },
    quantityCount(quantityOne, quantityTwo, symbol) {
      let alen = String(quantityOne).split('.')[1] || ''; // 算出每个小数的小数点长度
      let weightLength = String(quantityTwo).split('.')[1] || ''; // 算出每个小数的小数点长度
      let length = alen.length >= weightLength.length ? alen.length : weightLength.length;
      let pow = Math.pow(10, length);
      let result = symbol === '+' ? (quantityOne * pow + quantityTwo * pow) / pow : (quantityOne * pow - quantityTwo * pow) / pow;
      return result;
    },
    iqcExamine(row) {
      this.model = {};
      this.$nextTick(() => {
        this.$refs.basicInfoForm.allDisabled = true;
        this.$refs.inspectionResultsRecordForm.allDisabled = true;
        this.$refs.inspectionResultsRecordOption;
      });
      this.inspectionPictureList = [];
      this.loading = true;
      getDetail(row.id)
        .then((res) => {
          this.basicInfoForm.id = this._get(res, 'data.data.id', '');
          this.basicInfoForm.documentNo = this._get(res, 'data.data.documentNo', '');
          this.basicInfoForm.sourceNo = this._get(res, 'data.data.sourceNo', '');
          this.basicInfoForm.partnerName = this._get(res, 'data.data.partnerName', '');
          this.basicInfoForm.partNo = this._get(res, 'data.data.partNo', '');
          this.basicInfoForm.partName = this._get(res, 'data.data.partName', '');
          this.basicInfoForm.examineMode = this._get(res, 'data.data.examineMode', '');
          this.basicInfoForm.sendExamineDate = this._get(res, 'data.data.sendExamineDate', '');
          this.basicInfoForm.sendExamineQuantity = this._get(res, 'data.data.sendExamineQuantity', '');
          this.basicInfoForm.examineBy = this._get(res, 'data.data.examineBy', '');
          this.basicInfoForm.examineByName = this._get(res, 'data.data.examineByName', '');
          // 最小抽样数量
          const minSamplingQuantity = this._get(res, 'data.data.minSamplingQuantity', '');
          // 送检数量
          const sendExamineQuantity = this._get(res, 'data.data.sendExamineQuantity', '');
          // 检验数量
          const sampleQuantity = this._get(res, 'data.data.calculateQcInfoVO.sampleQuantity', '');
          // 收料数量 小于 最小抽样数量，按照全检的方式处理、
          if (sendExamineQuantity && minSamplingQuantity && Number(sendExamineQuantity) <= Number(minSamplingQuantity)) {
            this.basicInfoForm.examineMode = 'FULLINSPECTION';
          }
          if (sendExamineQuantity && sampleQuantity && Number(sendExamineQuantity) < Number(sampleQuantity)) {
            this.basicInfoForm.examineMode = 'FULLINSPECTION';
          }
          // this.$set(this.sampleInfoForm, 'code', this._get(res, 'data.data.qmsAqlScheme.code', ''));
          // this.$nextTick(() => {
          this.sampleInfoForm.code = this._get(res, 'data.data.qmsAqlScheme.code', '');
          this.sampleInfoForm.name = this._get(res, 'data.data.qmsAqlScheme.name', '');
          this.sampleInfoForm.samplingStandard = this._get(res, 'data.data.qmsAqlScheme.samplingStandard', '');
          this.sampleInfoForm.severityCode = this._get(res, 'data.data.qmsAqlScheme.severityCode', '');
          this.sampleInfoForm.levelType = this._get(res, 'data.data.qmsAqlScheme.levelType', '');
          this.sampleInfoForm.levelCode = this._get(res, 'data.data.qmsAqlScheme.levelCode', '');
          this.sampleInfoForm.limitCode = this._get(res, 'data.data.qmsAqlScheme.limitCode', '');
          this.sampleInfoForm.severityLimitCode = this._get(res, 'data.data.qmsAqlScheme.severityLimitCode', '');
          this.sampleInfoForm.majorLimitCode = this._get(res, 'data.data.qmsAqlScheme.majorLimitCode', '');
          this.sampleInfoForm.minorLimitCode = this._get(res, 'data.data.qmsAqlScheme.minorLimitCode', '');
          this.sampleInfoForm.sampleQuantity = this._get(res, 'data.data.calculateQcInfoVO.sampleQuantity', '');
          this.sampleInfoForm.acQuantity = this._get(res, 'data.data.calculateQcInfoVO.acQuantity', '');
          this.sampleInfoForm.reQuantity = this._get(res, 'data.data.calculateQcInfoVO.reQuantity', '');
          // });
          this.calculateQcInfoVOList = this._get(res, 'data.data.calculateQcInfoVO.calculateQcInfoVOList', []);
          this.basicInfoForm.examineBy = this.basicInfoForm.examineBy ? this.basicInfoForm.examineBy : JSON.parse(localStorage.getItem('saber-userInfo')).content.user_id;
          this.basicInfoForm.examineByName = this.basicInfoForm.examineByName
            ? this.basicInfoForm.examineByName
            : JSON.parse(localStorage.getItem('saber-userInfo')).content.user_name;
          this.inspectionResultsRecordForm.ngQuantity = this._get(res, 'data.data.ngQuantity', '');
          let attachments = this._get(res, 'data.data.qmsInspectionAttachmentList', []);
          if (attachments != null) {
            this._forEach(attachments, (item) => {
              this.inspectionResultsRecordForm.attachments.push({
                attachmentId: item.attachmentId,
                link: item.link,
                attachmentName: item.attachmentName,
                attachmentType: 'INSPECTION',
                value: item.link,
                label: item.attachmentName
              });
              this.inspectionPictureList.push({
                name: item.attachmentName,
                url: item.link
              });
            });
          }
          this.inspectionResultsRecordForm.examineResult = this._get(res, 'data.data.examineResult', '');
          this.inspectionResultsRecordForm.okQuantity =
            this.basicInfoForm.examineMode === 'SAMPLING' ? this.sampleInfoForm.sampleQuantity : this.basicInfoForm.sendExamineQuantity;
          this.inspectionResultsRecordForm.remark = this._get(res, 'data.data.remark', '');
          this.failureRecordData = this._get(res, 'data.data.qmsInspectionExceptionVoList', []);
          if (this.failureRecordData === null) {
            this.failureRecordData = [];
          }
          if (this.failureRecordData != null) {
            this._forEach(this.failureRecordData, (item) => {
              (item.qmsInspectionExceptionDetailList = this._map(this._cloneDeep(item.qmsInspectionExceptionDetailList), (itemObj) => {
                let obj = {};
                if (itemObj.dictType === 'FAILURE') {
                  obj.dictType = 'FAILURE';
                  obj.dictId = itemObj.dictId;
                  obj.dictCode = itemObj.dictCode;
                  obj.dictName = itemObj.dictName;
                  obj.remark = itemObj.remark;
                } else {
                  if (itemObj.subType === 'MAIN') {
                    obj.dictType = 'CAUSE';
                    obj.subType = 'MAIN';
                    obj.dictId = itemObj.dictId;
                    obj.dictCode = itemObj.dictCode;
                    obj.dictName = itemObj.dictName;
                    obj.remark = itemObj.remark;
                  } else {
                    obj.dictType = 'CAUSE';
                    obj.subType = 'SUB';
                    obj.dictId = itemObj.dictId;
                    obj.dictCode = itemObj.dictCode;
                    obj.dictName = itemObj.dictName;
                    obj.remark = itemObj.remark;
                  }
                }
                return obj;
              })),
                (item.qmsInspectionAttachmentList = this._map(item.qmsInspectionAttachmentList, (attachmentItem) => {
                  return {
                    attachmentId: attachmentItem.attachmentId,
                    link: attachmentItem.link,
                    attachmentName: attachmentItem.attachmentName,
                    attachmentType: 'INSPECTION'
                  };
                }));
            });
          }
        })
        .finally(() => {
          this.loading = false;
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.dialog-title {
  position: relative;
  .title {
    display: inline-block;
  }
  .fullscreen-icon {
    position: absolute;
    right: 20px;
    cursor: pointer;
    display: inline-block;
    font-size: 14px;
    color: #909399;
    &:hover {
      color: #0a84ff;
    }
  }
}

.fullscreen {
  ::v-deep .el-dialog {
    width: 100%;
    margin: 0 !important;
    margin-top: 0vh !important;
  }
}
.no_fullScreen {
  ::v-deep.el-dialog {
    width: 50%;
    margin-top: 5vh !important;
  }
}
</style>
